package com.loveofsoftware.fotolab;

import java.util.logging.Level;
import java.util.logging.Logger;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.bala.R;
import com.loveofsoftware.fotolab.CardView;
import com.loveofsoftware.fotolab.FileSaveDialog;
import com.loveofsoftware.fotolab.FotoView;
import com.loveofsoftware.fotolab.HorizontalSlider;
import com.loveofsoftware.fotolab.PreferencesActivity;
import com.loveofsoftware.fotolab.Util;
import com.loveofsoftware.fotolab.HorizontalSlider.OnProgressChangeListener;
import com.loveofsoftware.fotolab.effects.RotateEffect;
import com.loveofsoftware.fotolab.gestures.AdvancedGestureDetector;

public class EffectActivity extends Activity {

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mMode = MODE_NO_IMAGE;
		System.out.println("onDestroy, mode is : " + mMode);
	}

	@Override
	protected void onPause() {
		super.onPause();
		System.out.println("onPause, mode is : " + mMode);
	}

	@Override
	protected void onStart() {
		super.onStart();
		System.out.println("onStart, mode is : " + mMode);
	}

	@Override
	protected void onStop() {
		super.onStop();
		System.out.println("onStop, mode is : " + mMode);
	}

	// Show select file on every alternate call to activity - takes care of two
	// navigations
	boolean bAlternate = true;
	String lastFileSaved = null;

	@Override
	protected void onPostResume() {
		super.onPostResume();
		System.out.println("Mode in postResume : " + mMode);
		if (bAlternate && mMode == MODE_NO_IMAGE)
			selectFile();
		bAlternate = !bAlternate;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		View view = findViewById(R.id.foto_view);
		if (null != view)
			((FotoView) view).onSaveInstanceState(outState);
		System.out.println("Saving mode in OnSaveInstanceState : " + mMode);
		outState.putInt("MODE", mMode);
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (mMode != MODE_NO_IMAGE && detector.onTouchEvent(event))
			return true;
		return super.onTouchEvent(event);
	}

	private static final int SELECT_PICTURE = 1;
	private static final int REQUEST_SAVE = 2;
	private static final int REQUEST_LOAD = 3;

	public static AdvancedGestureDetector advDetector = new AdvancedGestureDetector();
	public static GestureDetector detector = new GestureDetector(advDetector);

	View.OnTouchListener gestureListener;

	public static String textOverlay = "";
	public static int textOverlayLeft = 0;
	public static int textOverlayTop = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.effect_main);
		advDetector.init(this);

		if (savedInstanceState != null) {
			mMode = savedInstanceState.getInt("MODE");
			System.out.println("Retrieved mode in OnCreate : " + mMode);
			if (mMode != MODE_NO_IMAGE) {
				if (!((FotoView) findViewById(R.id.foto_view))
						.restore(savedInstanceState)) {
					mMode = MODE_NO_IMAGE;
					System.out.println("Mode as fotoview restone failed : "
							+ mMode);
				}
			}
		}
		initModes();
	}

	private void selectFile() {

		Bundle extras = getIntent().getExtras();
		String filename = null;
		if (null != extras) {
			filename = extras.getString("fileFromCamera");
			extras.remove("fileFromCamera");
			getIntent().removeExtra("fileFromCamera");
		}
		if (filename != null && filename.length() > 0) {
			FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
			if (null == fotoView) {
				Resources res = getResources();
				Toast.makeText(getApplicationContext(),
						res.getString(R.string.errInternal), Toast.LENGTH_SHORT)
						.show();
				mMode = MODE_NO_IMAGE;
				System.out
						.println("ERROR, fotoView/selectedImagePath after selectPicture : "
								+ fotoView + "," + filename);
				return;
			}
			mMode = MODE_EDIT;
			System.out.println("open camera picture successful, mode is : "
					+ mMode);

			String result = fotoView.openImage(filename);
			if (result != null) {
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_SHORT).show();
				mMode = MODE_NO_IMAGE;
				System.out
						.println("Could not open image after select picture, mode is : "
								+ mMode);
				return;
			}
			return;
		}
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		Resources res = getResources();
		startActivityForResult(
				Intent.createChooser(intent,
						res.getString(R.string.selectPicture)), SELECT_PICTURE);

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			if (requestCode == SELECT_PICTURE) {
				this.finish();
			}
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				String selectedImagePath = getPath(selectedImageUri);

				FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
				if (null == selectedImagePath || null == fotoView) {
					Resources res = getResources();
					Toast.makeText(getApplicationContext(),
							res.getString(R.string.errInternal),
							Toast.LENGTH_SHORT).show();
					mMode = MODE_NO_IMAGE;
					System.out
							.println("ERROR, fotoView/selectedImagePath after selectPicture : "
									+ fotoView + "," + selectedImagePath);
					return;
				}
				mMode = MODE_EDIT;
				System.out.println("Select picture successful, mode is : "
						+ mMode);

				String result = fotoView.openImage(selectedImagePath);
				if (result != null) {
					Toast.makeText(getApplicationContext(), result,
							Toast.LENGTH_SHORT).show();
					mMode = MODE_NO_IMAGE;
					System.out
							.println("Could not open image after select picture, mode is : "
									+ mMode);
				} else {
					Resources res = getResources();
					Toast.makeText(getApplicationContext(),
							res.getString(R.string.helpMsgOnFileOpen),
							Toast.LENGTH_SHORT).show();
				}
			} else if (requestCode == REQUEST_SAVE) {
				System.out.println("Saving...");
				lastFileSaved = data.getStringExtra(FileSaveDialog.RESULT_PATH);
				FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
				fotoView.save(lastFileSaved);
				rescanMedia();// So that it is visible in gallery
			} else if (requestCode == REQUEST_LOAD) {
				System.out.println("Loading...");
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Logger.getLogger(EffectActivity.class.getName()).log(
						Level.WARNING, "file not selected");
			}

		}
	}

	private String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();

			return cursor.getString(column_index);
		} else
			return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.effect_menu, menu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.open:
			selectFile();
			return true;
		case R.id.save:
			save();
			return true;
		case R.id.saveAs:
			Intent intent = new Intent(this.getBaseContext(),
					FileSaveDialog.class);
			intent.putExtra(FileSaveDialog.START_PATH, Util.getFotolabDir(this));
			this.startActivityForResult(intent, REQUEST_SAVE);
			return true;
		case R.id.paintoptions:
			Intent intent1 = new Intent(this, PreferencesActivity.class);
			startActivity(intent1);
			return true;
		case R.id.exit:
			this.finish();
			mMode = MODE_NO_IMAGE;
			System.out.println("Exit, mode is : " + mMode);
			return true;
		case R.id.scanMedia:
			rescanMedia();
			return true;
		case R.id.rotateImage:
			FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
			fotoView.initialImageEffectPreference = "Rotate";
			fotoView.getThread().applyEffect();
			return true;
		case R.id.share:
			if (null == lastFileSaved) {
				save();
			}
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			Uri screenshotUri = Uri.parse(lastFileSaved);

			sharingIntent.setType("image/png");
			sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
			startActivity(Intent.createChooser(sharingIntent, "via fotolab"));
			return true;
		default:
			return super.onContextItemSelected(item);
		}

	}

	public void rescanMedia() {
		sendBroadcast(new Intent(
				Intent.ACTION_MEDIA_MOUNTED,
				Uri.parse("file://" + Environment.getExternalStorageDirectory())));
	}

	public static final int MODE_EDIT = 0;
	public static final int MODE_COMMAND = 1;
	public static final int MODE_NO_IMAGE = 2;

	private static int mMode = MODE_NO_IMAGE;

	private void save() {
		System.out.println("Save, mode is : " + mMode);
		if (mMode != MODE_NO_IMAGE) {
			View v = findViewById(R.id.foto_view);
			if (null != v) {
				FotoView fotoView = (FotoView) v;
				lastFileSaved = Util.getNewName(fotoView.currentImageFilename, this);
				fotoView.save(lastFileSaved);
				Resources res = getResources();
				Toast.makeText(getApplicationContext(),
						res.getString(R.string.saved) + " "
								+ fotoView.currentImageFilename,
						Toast.LENGTH_LONG);
				rescanMedia();
			}
		}
	}

	public void toggleMode() {
		if (MODE_NO_IMAGE == mMode) {
			System.out
					.println("ERROR: Why was toggleMode called when no image");
			return;
		}
		mMode = mMode == MODE_EDIT ? MODE_COMMAND : MODE_EDIT;
		System.out.println("Toogled mode to : " + mMode);
		if (findViewById(R.id.EffectImageButton) == null) {
			System.out.println("No Effect Image button to show command mode"); // Seems
			// like
			// i
			// was
			// called
			// earlier
			// than
			// expected
			return;
		}
		switch (mMode) {
		case MODE_EDIT:
			findViewById(R.id.EffectImageButton).setVisibility(View.INVISIBLE);
			findViewById(R.id.SaveImageButton).setVisibility(View.INVISIBLE);
			findViewById(R.id.PaletteImageButton).setVisibility(View.INVISIBLE);
			findViewById(R.id.TextImageButton).setVisibility(View.INVISIBLE);
			findViewById(R.id.SlidersImageButton).setVisibility(View.INVISIBLE);
			break;
		case MODE_COMMAND:
			findViewById(R.id.EffectImageButton).setVisibility(View.VISIBLE);
			findViewById(R.id.SaveImageButton).setVisibility(View.VISIBLE);
			findViewById(R.id.PaletteImageButton).setVisibility(View.VISIBLE);
			findViewById(R.id.TextImageButton).setVisibility(View.VISIBLE);
			findViewById(R.id.SlidersImageButton).setVisibility(View.VISIBLE);
			break;
		}
	}

	private void initModes() {

		final EditText editText = (EditText) findViewById(R.id.EditText01);
		if (null == editText) {
			System.out.println("ERROR: Why did not i get EditText01?");
			return;
		}

		editText.setOnEditorActionListener(new OnEditorActionListener() {

			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				textOverlay = editText.getText().toString();
				textOverlayLeft = editText.getLeft();
				textOverlayTop = editText.getTop();

				editText.setVisibility(View.INVISIBLE);
				editText.setText("");
				toggleMode();

				FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));

				CardView cardView = new CardView(getApplicationContext(),
						fotoView.getTextPaint(), textOverlay, textOverlayLeft,
						textOverlayTop);
				fotoView.addCardView(cardView);
				Resources res = getResources();
				Toast.makeText(getApplicationContext(),
						res.getString(R.string.helpMsgOnTextAdd),
						Toast.LENGTH_LONG).show();
				return true;
			}

		});
		((ImageButton) findViewById(R.id.TextImageButton))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						editText.setVisibility(View.VISIBLE);
					}

				});
		final Activity activity = this;
		((ImageButton) findViewById(R.id.EffectImageButton))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						Resources r = getResources();
						final String[] items = r
								.getStringArray(R.array.effectsArray);
						final String[] values = r
								.getStringArray(R.array.effectsValueArray);

						final boolean[] needsDegree = { false, false, false,
								false, false, false, false, false };

						AlertDialog.Builder builder = new AlertDialog.Builder(
								activity);
						Resources res = getResources();
						builder.setTitle(R.string.pickAnEffect);
						builder.setSingleChoiceItems(items, -1,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int item) {
										Toast.makeText(getApplicationContext(),
												items[item], Toast.LENGTH_SHORT)
												.show();
										FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
										fotoView.initialImageEffectPreference = values[item];
										fotoView.getThread().applyEffect();
										dialog.dismiss();
										toggleMode();
										if (needsDegree[item])
											;// showKnob();
									}
								});
						AlertDialog alert = builder.create();
						alert.show();

					}
				});
		((ImageButton) findViewById(R.id.SaveImageButton))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						save();

					}
				});

		((ImageButton) findViewById(R.id.SlidersImageButton))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						showSliders();
					}
				});

		((ImageButton) findViewById(R.id.PaletteImageButton))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						Resources r = getResources();
						final String[] items = r
								.getStringArray(R.array.colorsArray);
						final String[] values = r
								.getStringArray(R.array.colorsValueArray);

						AlertDialog.Builder builder = new AlertDialog.Builder(
								activity);
						Resources res = getResources();
						builder.setTitle(res.getString(R.string.pickAColor));
						builder.setSingleChoiceItems(items, -1,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int item) {
										Toast.makeText(getApplicationContext(),
												items[item], Toast.LENGTH_SHORT)
												.show();
										FotoView fotoView = ((FotoView) findViewById(R.id.foto_view));
										fotoView.colorPreference = values[item];
										dialog.dismiss();
									}
								});
						AlertDialog alert = builder.create();
						alert.show();
					}
				});

	}

	public void showSliders() {

		toggleMode();

		System.out.println("Application context is : "
				+ getApplicationContext());
		final Dialog dialog = new Dialog(this,
				android.R.style.Theme_Translucent_NoTitleBar);

		dialog.setContentView(R.layout.slider_controls);
		// dialog.setTitle("Image Controls");

		((HorizontalSlider) dialog.findViewById(R.id.colorSlider))
				.setNormalizedProgress(FotoView.colorMagnifyfactor
						/ FotoView.MAX_COLOR_MAGNIFY_FACTOR);
		((HorizontalSlider) dialog.findViewById(R.id.rotationSlider))
				.setNormalizedProgress(RotateEffect.deg / RotateEffect.MAX_DEG);
		((HorizontalSlider) dialog.findViewById(R.id.contrastSlider))
				.setNormalizedProgress((1 + FotoView.mContrast) / 2
						* FotoView.MAX_CONTRAST);
		((HorizontalSlider) dialog.findViewById(R.id.brightnessSlider))
				.setNormalizedProgress(FotoView.mBrightness
						/ FotoView.MAX_BRIGHTNESS);

		((HorizontalSlider) dialog.findViewById(R.id.contrastSlider))
				.setOnProgressChangeListener(new OnProgressChangeListener() {
					public void onProgressChanged(View v, int progress) {
						FotoView.setContrastAndBrightness(
								FotoView.MAX_CONTRAST
										* (((HorizontalSlider) dialog
												.findViewById(R.id.contrastSlider))
												.getNormalizedProgress() * 2 - 1),
								-1);
					}
				});
		((HorizontalSlider) dialog.findViewById(R.id.brightnessSlider))
				.setOnProgressChangeListener(new OnProgressChangeListener() {
					public void onProgressChanged(View v, int progress) {
						FotoView.setContrastAndBrightness(
								-2,
								FotoView.MAX_BRIGHTNESS
										* ((HorizontalSlider) dialog
												.findViewById(R.id.brightnessSlider))
												.getNormalizedProgress());
					}
				});
		((HorizontalSlider) dialog.findViewById(R.id.colorSlider))
				.setOnProgressChangeListener(new OnProgressChangeListener() {
					public void onProgressChanged(View v, int progress) {
						FotoView.colorMagnifyfactor = FotoView.MAX_COLOR_MAGNIFY_FACTOR
								* ((HorizontalSlider) dialog
										.findViewById(R.id.colorSlider))
										.getNormalizedProgress();
						System.out.println("Color is set to : "
								+ FotoView.colorMagnifyfactor);
					}
				});
		((HorizontalSlider) dialog.findViewById(R.id.rotationSlider))
				.setOnProgressChangeListener(new OnProgressChangeListener() {
					public void onProgressChanged(View v, int progress) {
						RotateEffect.deg = RotateEffect.MAX_DEG
								* ((HorizontalSlider) dialog
										.findViewById(R.id.rotationSlider))
										.getNormalizedProgress();
					}
				});
		dialog.show();

	}
}